/**********************************************************************
 2.申请单-配件借出申请

*************************************************************************/
public  without sharing class PartsLendingApplicationController {
   public String msg {get; private set;}
   public Boolean isErr {get; private set;}
   public Boolean isSuccess {get;private set ;}

   public String backId {get;private set;}

   public String dataJson {get;private set;}
   public String saveJson {get; set;}
   public String searchJson {get; set;}
   private Boolean isNew ;
   public  Boolean isDealer {get; private set;}//是否为经销商配件借出
   private  Map<String,DataUtil.SObjectBean> stageObjectMap;
    public Boolean isAssit {get; private set;}//当前操作人是否为助理

   private PartsLendingApplication__c papp ;

   public PartsLendingApplicationController(ApexPages.StandardController stdController){
   		isNew = false;
   		backId  = System.currentPageReference().getParameters().get('id');
   		papp = new PartsLendingApplication__c();
      stageObjectMap = new  Map<String,DataUtil.SObjectBean>();


   }
   public PartsLendingApplicationController(){
   		isNew = false;
   		backId  = System.currentPageReference().getParameters().get('id');
   		papp = new PartsLendingApplication__c();
      stageObjectMap = new  Map<String,DataUtil.SObjectBean>();

   }
   public void init(){

   		try {

          User cu = [select Id,ClientCode__c,EngineeringAssistant__c,Profile.Name  from User where Id =:UserInfo.getUserId()];
          isAssit = cu.EngineeringAssistant__c;
          String accNumber = '';
   		    if(String.isBlank(backId)){
   		    	  backId = '';
   		    	  isNew = true;
              isDealer = cu.ClientCode__c != null ;
              accNumber = cu.ClientCode__c;
   		    }else if(Id.valueOf(backId).getSobjecttype() == PartsLendingApplication__c.Sobjecttype ){//编辑
   		    	  
              papp = [select Id,OwnerId,NotificationAssistant__c, IsSycToNc__c  from PartsLendingApplication__c where Id =:backId];
              
              User u = [select Id,ClientCode__c from User where Id =:papp.OwnerId ];
              isDealer =u.ClientCode__c != null;
              accNumber = u.ClientCode__c;
              if(!isAssit && !cu.Profile.Name.contains('管理员') && papp.NotificationAssistant__c != null )throw new DmlException('已通知助理不能修改!');
              if( papp.IsSycToNc__c == true  )throw new DmlException('已同步NC不能修改!');

   		    }else {//新建
   		    	
   		    	//c = [select Id,AccountId,Account.Name  from Case where Id =:backId ];
   		    	throw new DmlException('页面打开错误!');
   		    }

          List<Account> accs = [select Id ,Name from Account where AccountNumber =:accNumber];
          if(accs.isEmpty() && isDealer ) throw new DmlException('请联系管理员维护用户信息的对应客户编码!');

   		    Map<String,Object> dataMap = new Map<String,Object>();
        	
        	dataMap.put('detail', getDetails());
			//dataMap.put('combobox',getCombox('ContractChangeList__c',new Set<String>{'AlterType__c','CooperateType__c','WhetherAddInstrument__c'}));
    	   	dataMap.put('searchObject',getSearchObject());
                    //字段
             Map<String,Set<String>> fieldsmap = getFields();
             //字段详情
             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
            
            //字段赋值
             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
           
              //后续处理方式为“经销商备用”，申请库存组织默认为“四川省迈克实业有限公司”，“开票客户”、“终端客户”默认为本经销商（通过用户上的客户编码查找的客户）
              //，且只能选择品牌为迈克的配件

              for (DataUtil.FieldBean fb   :  fields.get('PartsLendingApplication__c')) {
                Map<String,Object> vMap  = new Map<String,Object>();
                 if(isDealer){
                    if(fb.name == 'TerminalClient__c'){

                        vMap.put('Id', accs[0].Id );
                        vMap.put('Name', accs[0].Name );
                        fb.value = vMap;
                    }
                    if(fb.name == 'InvoicingCustomers__c'){

                        vMap.put('Id', accs[0].Id );
                        vMap.put('Name', accs[0].Name );
                        fb.value = vMap;
                    }
                    

                    if(fb.name == 'InventoryOrganization__c')fb.value = 'MKSY';
                    if(fb.name == 'FollowupProcessing__c')fb.value = '经销商备用'; 
                  }

                
                if(fb.name == 'DocumentTypes__c')fb.value = '库存借出';
             }

            
            dataMap.put('base',fields);
            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 

        	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap ),'UTF-8');



   		}catch (Exception e) {
   		    isErr = true ;
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
   		}
   		
   }


    public Map<String,Set<String>>  getFields(){
        Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

            sb.title ='';
            sb.objname = 'PartsLendingApplication__c';
            sb.stype = DataUtil.getSObjectType( sb.objname);
            if(!isNew)sb.idvalue = backId;
            sb.type = 'base';
            if(!isNew)sb.condition = ' where Id =\''+backId +'\'';
            stageObjectMap.put( sb.objname,sb );
            Set<String>  fields = new Set<String>{'TerminalClient__c','FollowupProcessing__c','InvoicingCustomers__c','DocumentTypes__c',
            		'Phone__c','InstallmentSale__c','ReceivingRemarks__c','PhysicalDelivery__c','InventoryOrganization__c','Remark__c'
        		};
         
            fieldsMap.put('PartsLendingApplication__c', fields);
        
        return fieldsMap;
    }

     private Map<String ,Map<String,String>> getCombox(String objName ,Set<String> fields ){
    	Map<String ,Map<String,String>> tmp = new Map<String ,Map<String,String>>();
    	for(String f : fields){
    		Map<String,String> pickMap = ImportObject.getPicklistValues(objName, f, true);
    		tmp.put(f, pickMap);
    	}
    	return tmp;
    } 

     private Map<String,List<DataUtil.FieldBean>> getSearchObject(){
    	Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

    	Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Product__c.SObjecttype, new Set<String>{'ProductName__c','Brand__c','Spec__c','Model__c','NCCode__c','SerialNo__c','Category0__c','Category1__c'} );
    	searchMap.put('Product__c', proMap.values());
    	return searchMap;
    }

    public void searchProduct(){
    	Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));

       // String sealflag  =  'Y-'+ mcon.Corpcode__c;

    	String sql = ' select Id ,Name,Model__c ,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c ,Category1__c ,SealCompany__c,MatchingInstrument__c,NCinvshortname__c  from Product__c where  RecordType.DeveloperName =\'NCProduct\' and NCCode__c != null and (Category0__c=\'耗材\' or Category3__c=\'配件\') ';
    	
    	//sql += ' and Id  not in (select Product__c from ContractProduct__c where Contract__c =\''+mcon.MainContract__c+'\'  ) and  (not SealCompany__c  like \'%'+sealflag+'%\') ';

    	//sql += ' and Category0__c = \'仪器\'  and PriceCompany__c like \'%'+ mcon.Corpcode__c+'%\' ';
    	if(isDealer) sql += ' and Brand__c in '+MaccuraBrandUtil.getMaccuraInStr()+' and ProhibitionChoice__c != true  ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('ProductName__c'))) == false) sql += ' and ProductName__c like \'%'+DataUtil.getStringValue(searchMap.get('ProductName__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Brand__c'))) == false) sql += ' and Brand__c like \'%'+DataUtil.getStringValue(searchMap.get('Brand__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Spec__c'))) == false) sql += ' and Spec__c like \'%'+DataUtil.getStringValue(searchMap.get('Spec__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('SerialNo__c'))) == false) sql += ' and SerialNo__c like \'%'+DataUtil.getStringValue(searchMap.get('SerialNo__c'))+'%\' ';
 
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category0__c'))) == false) sql += ' and Category0__c like \'%'+DataUtil.getStringValue(searchMap.get('Category0__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category1__c'))) == false) sql += ' and Category1__c like \'%'+DataUtil.getStringValue(searchMap.get('Category1__c'))+'%\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('NCCode__c'))) == false) sql += ' and NCCode__c like \'%'+DataUtil.getStringValue(searchMap.get('NCCode__c'))+'%\' ';

    	sql += ' limit 200 ';
    	System.debug('PartsLendingApplicationController==>'+sql);
    	  List<ProductBean> tmp = new List<ProductBean>();
          for (Product__c  p : Database.query(sql)) {
          		tmp.add(new ProductBean(p));
          }


	      dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    }
   public void setNil(){
   		dataJson = '[]';
   		saveJson = '{}';
   		searchJson = '{}';
   		 
   }

   private List<ProductBean>  getDetails(){
   		List<ProductBean> tmp = new List<ProductBean>();
   		for(PartsLendingDetails__c p : [select Id , Product__c , Product__r.Name,Product__r.Spec__c , Product__r.Brand__c , 
	   		Product__r.Model__c,Product__r.SerialNo__c,No__c ,Product__r.NCCode__c 
	   		from PartsLendingDetails__c where PartsLendingApplication__c =:backId  ]){

   			tmp.add(new ProductBean(p));
   		}
   		return tmp;
   }


   public void save(){
   		msg = '';
   		try {

   			Map<String,Object>saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
	        Map<String,Set<String>> fieldsMap = getFields();
	        Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(PartsLendingApplication__c.SObjecttype,fieldsMap.get('PartsLendingApplication__c'));


	            Map<String,Object> obj = (Map<String,Object>) saveMap.get('base');

	            for (String field :  obj.keySet()) {

	                if(obj.get(field) == null || DataUtil.getStringValue(obj.get(field)) == '') continue;

	                if(fbeanMap.containsKey(field) )papp.put(field, DataUtil.dataHandler(obj.get(field),fbeanMap.get(field).type.toUpperCase() ));

	            }
	        List<Object> saveList = (List<Object>) saveMap.get('datas');
	        List<PartsLendingDetails__c> details = new List<PartsLendingDetails__c>();
	        Set<String> exDetailset = new Set<String>();
	        for (Object o  : saveList) {
	          	Map<String,Object> mo = (Map<String,Object>)o;
	          	PartsLendingDetails__c pd = new PartsLendingDetails__c();
	          	pd.Id = DataUtil.getStringValue(mo.get('detailId'));
	          	if(pd.Id != null )  exDetailset.add(pd.Id);
	          	pd.Product__c = DataUtil.getStringValue(mo.get('productId'));
	          	pd.No__c = DataUtil.getDecimalValue(mo.get('num'));
	          	details.add(pd);
	        }  
	            
	        SavePoint sp = Database.setSavepoint();
	        try {
	          if(isNew )papp.Id = null;
	        	upsert papp ;
	        	delete [select Id from PartsLendingDetails__c where Id not in: exDetailset and PartsLendingApplication__c =:papp.Id  ];
	        	
	        	for (PartsLendingDetails__c pd  : details) {
	        		if(pd.Id == null )pd.PartsLendingApplication__c = papp.Id;	
	        	}
	        	if(!details.isEmpty() )upsert details;

	        	isSuccess = true;
	        	msg = '保存成功!';
	        	backId = papp.Id;
	        }
	        catch (Exception e) {
   		   	 	msg = '保存失败:'+e.getMessage()+e.getStackTraceString();
   		   	 	Database.rollback(sp);
	        }
	        
   		    
   		}catch (Exception e) {
   		    msg = '保存失败:'+e.getMessage()+e.getStackTraceString();

   		}
   		
        
   }


   public class ProductBean{

   		public String productId ;
   		public String productName;
   		public String spec ;
   		public String brand ;
   		public String model;
   		public String serialno ;
   		public String nccode;
   		public String detailId; 
   		public Decimal num;

   		public ProductBean(Product__c p ){
   			productId = p.Id;
   			productName = p.Name;
   			spec = p.Spec__c;
   			brand = p.Brand__c;
   			model = p.Model__c;
   			serialno = p.SerialNo__c;
   			nccode = p.NCCode__c;

   		}
   		public ProductBean (PartsLendingDetails__c p){
   			productId = p.Product__c;
   			productName = p.Product__r.Name;
   			spec = p.Product__r.Spec__c;
   			brand = p.Product__r.Brand__c;
   			model = p.Product__r.Model__c;
   			serialno = p.Product__r.SerialNo__c;
        nccode = p.Product__r.NCCode__c;
   			detailId  = p.Id;
   			num = p.No__c;
   		}
   }




}